package com.weixin.demo.kotlinboot.controllers

import com.weixin.demo.kotlinboot.bean.User
import com.weixin.demo.kotlinboot.dao.UserRepository
import com.weixin.demo.kotlinboot.dao.VideoRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.*


@Controller
@RequestMapping("/")
class HomeController {
    @Autowired
    lateinit var repository: UserRepository

    @Autowired
    lateinit var video: VideoRepository

    @RequestMapping(value = "/index", method = arrayOf(RequestMethod.GET))
    fun index(pageModal: ModelMap): String {
        pageModal["data"] = "success"
        return "index"
    }

    @RequestMapping("/add/{id}/{firstName}/{lastName}")
    fun add(model: Model, @PathVariable("id") id: Long, @PathVariable("firstName") firstName: String, @PathVariable("lastName") lastName: String): String {
        repository.save(User(id, firstName, lastName))
        model.addAttribute("id", id)
        return "add"
    }

    @GetMapping("/get/id/{id}")
    fun getbyId(model: Model, @PathVariable("id") id: Long): String {
        val user = repository.findOne(id)
        model.addAttribute("user", user)
        return "view"
    }

    @GetMapping("/get/name/{lastName}")
    fun getByLastName(model: Model, @PathVariable("lastName") lastName: String): String {
        val users = repository.findByLastName(lastName)
        return setModel(model, users)
    }


    @GetMapping("/get/{author}")
    fun getVideo(model: Model, @PathVariable("author") name: String): String {
        val users = video.findUser(name)
        return users.toString()
    }

    private fun setModel(model: Model, users: List<User>): String {
        model.addAttribute("users", users)
        return "list"
    }
}